<?php
namespace app\massage\controller;
use app\AdminRest;
use app\massage\model\BalanceWater;
use app\massage\model\Bonus;
use app\massage\model\Coach;
use app\massage\model\Commission;
use app\massage\model\CommShare;
use app\massage\model\Identity;
use app\massage\model\Order;
use app\massage\model\User;
use app\massage\model\UserLabelData;
use app\shop\model\Article;
use app\shop\model\Banner;
use app\shop\model\Date;
use app\massage\model\OrderGoods;
use app\massage\model\RefundOrder;
use app\shop\model\Wallet;
use think\App;
use app\massage\model\User as Model;
use think\facade\Db;


class AdminUser extends AdminRest
{


    protected $model;

    protected $order_goods_model;

    protected $refund_order_model;

    protected $comm_share_model;



    public function __construct(App $app) {

        parent::__construct($app);

        $this->model = new Model();

        $this->order_goods_model  = new OrderGoods();

        $this->refund_order_model = new RefundOrder();

        $this->comm_share_model   = new CommShare();

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-24 10:24
     * @功能说明:用户列表
     */
    public function userList(){

        $input = $this->_param;

        $dis[] = ['uniacid','=',$this->_uniacid];
        //是否授权
        if(!empty($input['type'])){

            if($input['type']==1){

                $dis[] = ['nickName','=',''];

            }else{

                $dis[] = ['nickName','<>',''];

            }

        }


        if(!empty($input['group_id'])){
            $dis[] = ['group_id','=',$input['group_id']];
        }
        $where = [];

        if(!empty($input['nickName'])){

            $where[] = ['nickName','like','%'.$input['nickName'].'%'];

            $where[] = ['phone','like','%'.$input['nickName'].'%'];
        }

        if(!empty($input['start_time'])&&!empty($input['end_time'])){

            $start_time = $input['start_time'];

            $end_time = $input['end_time'];

            $dis[] = ['create_time','between',"$start_time,$end_time"];
        }

        if(!empty($input['id'])){

            $dis[] = ['id','=',$input['id']];
        }

        if(!empty($input['phone'])){

            $dis[] = ['phone','like','%'.$input['phone'].'%'];
        }

        $data = $this->model->dataList($dis,$input['limit'],$where);

        if(!empty($data['data'])){
            $label_model = new UserLabelData();
            foreach ($data['data'] as &$v){
                $v['user_label'] = $label_model->getUserLabel($v['id']);
                $v['pname'] = $this->model->where(['id' => $v['pid']])->value('nickName') ?? '无';
            }
        }
        return $this->success($data);

    }

    //用户收支明细
    public function getBlanceRecord()
    {
        $id = $this->_param['id'] ?? 0;
        $page= $this->_param['page'] ?? 10;
        $recordModel = new BalanceWater();
        $dis = ['user_id' => $id];
        $data = $recordModel->dataList($dis,$page);
        return $this->success($data);
    }

    //用户详情
    public function detail()
    {
        $id = $this->_param['id'] ?? 0;
        $userModel = new User();
        $identityModel = new Identity();
        $dis = ['id' => $id];
        $user = $userModel->dataInfo($dis);
        $identityNames = $identityModel->where(['status' => 1])->column('name','id');
        $user['trueName'] = '';
        $user['bankNo'] = '';
        $user['bankName'] = '';
        $user['identityName'] = $identityNames[$user['identity_id']] ?? '普通会员';
        $user['userList'] = $userModel->where([['id','<>',$id]])->field('id,nickName')->select();
        $user['userList'][] = ['id' => 0,'nickName' => '无'];
        return $this->success($user);
    }

    //用户编辑
    public function updateParent()
    {
        $input = $this->_param;
        $userModel = new User();
        $res = $userModel->where(['id' => $input['id']])->update(['pid' => $input['pid']]);
        return $this->success('操作成功');
    }
    /**
     * @author chenniang
     * @DataTime: 2021-08-28 23:03
     * @功能说明:佣金记录
     */
    public function commList(){

        $input = $this->_param;

        $order_model = new Order();

        $order_model->coachBalanceArr($this->_uniacid);

        $dis[] = ['a.uniacid','=',$this->_uniacid];

        $dis[] = ['a.cash','>',0];

        if(!empty($input['status'])){

            $dis[] = ['a.status','=',$input['status']];
        }else{

            $dis[] = ['a.status','>',-1];

        }

        $where = [];

        if(!empty($input['top_name'])){

            $where[] = ['c.nickName','like','%'.$input['top_name'].'%'];

            $where[] = ['e.agent_name','like','%'.$input['top_name'].'%'];

            $where[] = ['f.coach_name','like','%'.$input['top_name'].'%'];

            $where[] = ['g.now_coach_name','like','%'.$input['top_name'].'%'];

            $where[] = ['h.user_name','like','%'.$input['top_name'].'%'];

            $where[] = ['m.user_name','like','%'.$input['top_name'].'%'];
        }

        if($this->_user['is_admin']==0){

            $dis[] = ['a.admin_id','in',$this->admin_arr];

        }

        if(!empty($input['type'])){

            if($input['type']==2){

                $dis[] = ['a.type','in',[2,5,6]];
            }else{

                $dis[] = ['a.type','=',$input['type']];
            }

        }

        if(!empty($input['order_code'])){

            $dis[] = ['d.order_code','like','%'.$input['order_code'].'%'];

        }

        $comm_model = new Commission();

        $data = $comm_model->recordListV2($dis,$where,$input['limit']);

        $admin_model = new \app\massage\model\Admin();

        $commission_custom = getConfigSetting($this->_uniacid,'commission_custom');

        if(!empty($data['data'])){

            foreach ($data['data'] as &$v){

                $v['nickName'] = $this->model->where(['id'=>$v['user_id']])->value('nickName');

                $v['coach_cash_control'] = $v['status']==2&&$v['admin_id']==0&&in_array($v['type'],[3,8])&&$v['top_id']==0?1:0;

                $v['cash'] = round($v['cash'] ,2);

                if($v['car_price']>0){

                    $v['pay_price'] = $v['pay_price'].'(含车费'.$v['car_price'].')';
                }

                if(in_array($v['type'],[2,5,6,11])){

                    $v['top_name'] = $v['admin_name'];

                }elseif (in_array($v['type'],[3,8])){

                    $v['top_name'] = $v['coach_name'];

                    if($v['top_id']==0&&$v['car_cash']>0){

                        $v['cash'] = $v['cash'].'(含车费'.$v['car_cash'].')';

                    }

                    if(empty($v['top_id'])){

                        $v['top_name'] = $v['now_coach_name'];
                    }

                }elseif ($v['type']==10){

                    $v['top_name'] = $v['channel_name'];

                }elseif ($v['type']==12){

                    $v['top_name'] = $v['salesman_name'];
                }

                if($v['type']==2){

                    if($commission_custom==0){

                        $v['balance'] = '平台抽成-'.$v['balance'];
                    }

                    $coach_cash = $v['coach_cash']>0?'包含'.$v['coach_cash'].'线下服务费，':'';

                    $car_cash   = $v['car_cash']>0?'包含'.$v['car_cash'].'线下车费':'';

                    $v['cash'] = !empty($coach_cash)||!empty($car_cash)?$v['cash'].'('.$coach_cash.$car_cash.')':$v['cash'];
                }

                $share_cash = 0;
                //技师查询是否有分摊金额
                if($v['type']==3){

                    $share_cash = $this->comm_share_model->where(['order_id'=>$v['order_id'],'type'=>1])->sum('share_cash');
                }
                //代理商分摊金额
                if(in_array($v['type'],[2,5,6])){

                    $share_cash = $this->comm_share_model->where(['order_id'=>$v['order_id'],'type'=>2,'share_id'=>$v['top_id']])->sum('share_cash');
                }

                if(!empty($share_cash)){

                    $v['cash'] .= '  被分摊金额:'.$share_cash.'元';
                }

            }

        }

        if($this->_user['is_admin']==0){
            //可提现记录
            $data['total_cash'] = $admin_model->where(['id'=>$this->_user['id']])->sum('cash');

            $dis = [

                'admin_id' => $this->_user['id'],

                'status'   => 1,

                'type'     => 2
            ];
            //未入账金额
            $data['unrecorded_cash'] = $comm_model->where($dis)->sum('cash');

            $wallet_model = new \app\massage\model\Wallet();

            $dis = [

                'user_id' => $this->_user['id'],

                'type'    => 3
            ];
            //加盟商提现
            $data['wallet_cash'] = $wallet_model->where($dis)->where('status','in',[1,2])->sum('total_price');
        }

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2023-03-15 18:25
     * @功能说明:代理商修改线下技师佣金记录状态
     */
    public function adminUpdateCoachCommisson(){

        $input = $this->_input;

        $dis = [

            'id' => $input['id']
        ];

        $comm_model = new Commission();

        $data = $comm_model->dataInfo($dis);

        if($data['status']!=2){

            $this->errorMsg('佣金还未到账');
        }

        $res = $comm_model->dataUpdate($dis,['cash_status'=>1]);

        return $this->success($res);

    }



    /**
     * @author chenniang
     * @DataTime: 2021-08-28 23:03
     * @功能说明:佣金记录
     */
    public function cashList(){

        $input = $this->_param;

        $order_model = new Order();

        $order_model->coachBalanceArr($this->_uniacid);

        $dis[] = ['a.uniacid','=',$this->_uniacid];

        $dis[] = ['a.cash','>',0];

        if(!empty($input['status'])){

            $dis[] = ['a.status','=',$input['status']];
        }else{

            $dis[] = ['a.status','>',-1];

        }

        $where = [];

        if(!empty($input['top_name'])){

            $where[] = ['c.nickName','like','%'.$input['top_name'].'%'];

            $where[] = ['e.agent_name','like','%'.$input['top_name'].'%'];

            $where[] = ['f.coach_name','like','%'.$input['top_name'].'%'];

            $where[] = ['g.now_coach_name','like','%'.$input['top_name'].'%'];

            $where[] = ['h.user_name','like','%'.$input['top_name'].'%'];

            $where[] = ['m.user_name','like','%'.$input['top_name'].'%'];
        }

        if($this->_user['is_admin']==0){

            $dis[] = ['a.admin_id','in',$this->admin_arr];

        }

        if(!empty($input['type'])){

            if($input['type']==2){

                $dis[] = ['a.type','in',[2,5,6]];

            }else{

                $dis[] = ['a.type','=',$input['type']];
            }

        }

        if(!empty($input['order_code'])){

            $dis[] = ['d.order_code','like','%'.$input['order_code'].'%'];

        }

        $comm_model = new Commission();

        $data = $comm_model->recordListV2($dis,$where,$input['limit']);

        $admin_model = new \app\massage\model\Admin();

        $commission_custom = getConfigSetting($this->_uniacid,'commission_custom');

        if(!empty($data['data'])){

            foreach ($data['data'] as &$v){

                $v['nickName'] = $this->model->where(['id'=>$v['user_id']])->value('nickName');

                if($v['car_price']>0){

                    $v['pay_price'] = $v['pay_price'].'(含车费'.$v['car_price'].')';
                }

                if(in_array($v['type'],[2,5,6,11])){

                    $v['top_name'] = $v['admin_name'];

                }elseif (in_array($v['type'],[3,8])){

                     $v['top_name'] = $v['coach_name'];

                    if($v['top_id']==0&&$v['car_cash']>0){

                        $v['cash'] = $v['cash'].'(含车费'.$v['car_cash'].')';

                    }

                    if(empty($v['top_id'])){

                        $v['top_name'] = $v['now_coach_name'];
                    }

                }elseif ($v['type']==10){

                    $v['top_name'] = $v['channel_name'];

                }elseif ($v['type']==12){

                    $v['top_name'] = $v['salesman_name'];

                }

                if($v['type']==2){

                    if($commission_custom==0){

                        $v['balance'] = '平台抽成-'.$v['balance'];
                    }

                    $coach_cash = $v['coach_cash']>0?'包含'.$v['coach_cash'].'线下服务费':'';

                    $car_cash   = $v['car_cash']>0?'包含'.$v['car_cash'].'线下车费':'';

                    $v['cash']  = !empty($coach_cash)||!empty($car_cash)?$v['cash'].'('.$coach_cash.$car_cash.')':$v['cash'];
                }

                $v['coach_cash_control'] = $v['status']==2&&$this->_user['id'] == $v['admin_id']&&in_array($v['type'],[3,8])&&$v['top_id']==0?1:0;

                $share_cash = 0;
                //技师查询是否有分摊金额
                if($v['type']==3){

                    $share_cash = $this->comm_share_model->where(['order_id'=>$v['order_id'],'type'=>1])->sum('share_cash');
                }
                //代理商分摊金额
                if(in_array($v['type'],[2,5,6])){

                    $share_cash = $this->comm_share_model->where(['order_id'=>$v['order_id'],'type'=>2,'share_id'=>$v['top_id']])->sum('share_cash');
                }

                if(!empty($share_cash)){

                    $v['cash'] .= '  被分摊金额:'.$share_cash.'元';
                }
            }

        }

        if($this->_user['is_admin']==0){
            //可提现记录
            $data['total_cash'] = $admin_model->where(['id'=>$this->_user['id']])->sum('cash');

            $dis = [

                'admin_id' => $this->_user['id'],

                'status'   => 1,
            ];
            //未入账金额
            $data['unrecorded_cash'] = $comm_model->where($dis)->where('type','in',[2,5,6])->sum('cash');

            $wallet_model = new \app\massage\model\Wallet();

            $dis = [

                'user_id' => $this->_user['id'],

                'type'    => 3
            ];
            //加盟商提现
            $data['wallet_cash'] = $wallet_model->where($dis)->where('status','in',[1,2])->sum('total_price');

            $data['total_cash'] = round($data['total_cash'],2);

            $data['unrecorded_cash'] = round($data['unrecorded_cash'],2);

            $data['wallet_cash'] = round($data['wallet_cash'],2);
        }

        return $this->success($data);

    }




    /**
     * @author chenniang
     * @DataTime: 2021-03-24 13:33
     * @功能说明:团长审核提现
     */
    public function applyWallet(){

        $input = $this->_input;

        if(empty($input['apply_price'])||$input['apply_price']<0.01){

            $this->errorMsg('提现费最低一分');
        }

        if($this->_user['is_admin']!=0){

            $this->errorMsg('只有加盟商才能提现');

        }

        $admin_model = new \app\massage\model\Admin();

        $admin_user = $admin_model->dataInfo(['id'=>$this->_user['id']]);
        //服务费
        if($input['apply_price']>$admin_user['cash']){

            $this->errorMsg('余额不足');
        }
        //获取税点
        $tax_point = getConfigSetting($this->_uniacid,'tax_point');

        $balance = 100-$tax_point;

        $key = 'admin_cash_wallet'.$this->_user['id'];

        incCache($key,1,$this->_uniacid);

        $value = getCache($key,$this->_uniacid);

        if($value!=1){
            //减掉
            decCache($key,1,$this->_uniacid);

            $this->errorMsg('网络错误，请刷新重试');

        }

        Db::startTrans();
        //减佣金
        $res = $admin_model->dataUpdate(['id'=>$this->_user['id'],'lock'=>$admin_user['lock']],['cash'=>$admin_user['cash']-$input['apply_price'],'lock'=>$admin_user['lock']+1]);

        if($res!=1){

            Db::rollback();
            //减掉
            decCache($key,1,$this->_uniacid);

            $this->errorMsg('申请失败');
        }

        $insert = [

            'uniacid'       => $this->_uniacid,

            'user_id'       => $admin_user['id'],

            'admin_id'      => $admin_user['id'],

            'coach_id'      => 0,

            'total_price'   => $input['apply_price'],

            'balance'       => $balance,

            'apply_price'   => round($input['apply_price']*$balance/100,2),

            'service_price' => round( $input['apply_price'] * $tax_point / 100, 2),

            'tax_point'     => $tax_point,

            'code'          => orderCode(),

            'text'          => !empty($input['text'])?$input['text']:'',

            'type'          => 3,

        ];

        $wallet_model = new \app\massage\model\Wallet();
        //提交审核
        $res = $wallet_model->dataAdd($insert);

        if($res!=1){

            Db::rollback();
            //减掉
            decCache($key,1,$this->_uniacid);

            $this->errorMsg('申请失败');
        }

        Db::commit();
        //减掉
        decCache($key,1,$this->_uniacid);

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2022-10-24 16:44
     * @功能说明:删除用户标签
     */
    public function delUserLabel(){

        $input = $this->_input;

        $label_model = new UserLabelData();

        $res = $label_model->dataUpdate(['user_id'=>$input['user_id'],'label_id'=>$input['label_id']],['status'=>-1]);

        return $this->success($res);

    }




    /**
     * @author chenniang
     * @DataTime: 2021-03-24 10:24
     * @功能说明:用户列表
     */
    public function userSelectByPhone(){

        $input = $this->_param;

        $dis[] = ['uniacid','=',$this->_uniacid];
        //如果是代理商 必须要传手机号
        if($this->_user['is_admin']==0&&empty($input['phone'])){

            $dis[] = ['id','=',-2];
        }
        $where = [];
        //手机号精准搜索
        if(!empty($input['phone'])){

            $where[] = ['phone','=',$input['phone']];

            $where[] = ['nickName','=',$input['phone']];
        }

        $data = $this->model->dataList($dis,$input['limit'],$where);

        return $this->success($data);

    }

    //佣金明细列表
    public function bonusList()
    {
        $bonus_model = new Bonus();
        $input = $this->_param;
        $where = [];
        //用户ID
        if(isset($input['user_id']) && $input['user_id']){
            $where[] = ['u.id','=',$input['user_id']];
        }
        //佣金类型
        if(isset($input['type_id']) && $input['type_id']){
            $where[] = ['b.type','=',$input['type_id']];
        }
        //发放状态
        if(isset($input['send_status']) && $input['send_status']){
            $where[] = ['b.send_status','=',$input['send_status']];
        }
        //开始时间
        if(isset($input['start_time']) && $input['start_time']){
            $where[] = ['t.create_time','>=',$input['start_time']];
        }
        //结束时间
        if(isset($input['end_time']) && $input['end_time']){
            $where[] = ['t.create_time','<',$input['end_time']];
        }
        $data =  $bonus_model->alias('b')
            ->join('massage_service_user_list u','u.id=b.user_id')
            ->join('massage_commission_type t','t.id=b.type')
            ->where($where)
            ->field('b.*,u.nickName,u.avatarUrl,u.phone,t.name as type_name')
            ->order('b.id asc')
            ->paginate($input['limit'])
            ->toArray();
        return $this->success($data);
    }

    //发放佣金
    public function sendBonus()
    {
        $bonus_model = new Bonus();
        $input = $this->_param;
        $ids = $input['ids'];
        $where = [
            ['id','in',$ids],
            ['send_status','=',0]
        ];
        $bonus_list = $bonus_model->where($where)->select();
        $user_model = new User();
        foreach ($bonus_list as $bonus) {
            $where = ['id' => $bonus['user_id']];
            $user = $user_model->dataInfo($where);
            $cash = $user['cash'] + $bonus['bonus'];
            $new_cash = $user['new_cash'] + $bonus['bonus'];
            $res = $user_model->dataUpdate($where,['cash' => $cash,'new_cash' => $new_cash]);
            if($res){
                $bonus_model->dataUpdate(['id' => $bonus['id']],['send_status' => 1]);
            }
        }
        return $this->success([]);
    }
}
